#!/usr/bin/perl
use FindBin;
use lib "$FindBin::Bin/../lib";
use lib "$FindBin::Bin/../lib/perl-lib/lib/perl5";

use strict;
use Getopt::Long;
use AutoExecUtils;
use SqlplusExec;

#把原主库切换为StandBy
#input：
#db主机节点（DB主节点）
#sid: oracle实例的SID, 用于设置环境变量ORACLE_SID，如果不提供使用原环境变量的ORACLE_SID

#output:
#无，如果检查失败会返回失败

sub usage {
    my $pname = $FindBin::Script;

    print("$pname --sid <sid>\n");
    exit(1);
}

sub switchToStandby {
    my ($sid) = @_;

    #alter database commit to switchover to physical standby with session shutdown;
    my $hasError = 0;
    my $sqlplus  = SqlplusExec->new( sid => $sid );

    print("INFO: Try to switch to standby...\n");
    $sqlplus->do(
        sql     => qq{alter database commit to switchover to physical standby with session shutdown},
        verbose => 1
    );

    my $switched  = 0;
    my $loopCount = 300;
    while ( $switched == 0 and $loopCount > 0 ) {
        my $rows = $sqlplus->query(
            sql     => q{SELECT SWITCHOVER_STATUS FROM V$DATABASE},
            verbose => 1
        );

        my $switchoverStatus = '';
        if ($rows) {
            $switchoverStatus = $$rows[0]->{SWITCHOVER_STATUS};
        }
        if ( $switchoverStatus eq 'TO PRIMARY' or $switchoverStatus eq 'SESSIONS ACTIVE' ) {
            $switched = 1;
            print("FINE: Switch success.\n");
        }
        sleep(2);
        $loopCount--;
    }
    if ( $loopCount <= 0 ) {
        $hasError = 1;
        print("ERROR: Wait the db instance switchover status to 'TO PRIMARY' or 'SESSIONS ACTIVE' timeout.\n");
    }

    return $hasError;
}

sub main {
    AutoExecUtils::setEnv();
    my $opts = {};
    GetOptions(
        $opts, qw{
            sid=s
        }
    );

    my $hasError = switchToStandby( $opts->{sid} );
    return $hasError;
}

exit( main() );
